//
//  SMG_Dao.m
//  XGSmartHW
//
//  Created by 贾  on 2017/3/10.
//  Copyright © 2017年 XiaoGang. All rights reserved.
//

#import "SMG_Dao.h"
#import "WordConcrete.h"
#import "TMCache.h"

@implementation SMG_Dao

-(id) init{
    self = [super init];
    if (self) {
        [self initData];
    }
    return self;
}

-(void) initData{
    NSDictionary *oldNormalDic = [[TMCache sharedCache] objectForKey:@"SMG_Dao_NORMAL_LOCAL_KEY"];
    NSDictionary *oldCacheDic = [[TMCache sharedCache] objectForKey:@"SMG_Dao_CACHE_LOCAL_KEY"];
    self.normalDao = [[NSMutableDictionary alloc] initWithDictionary:oldNormalDic];
    self.cacheDao = [[NSMutableDictionary alloc] initWithDictionary:oldCacheDic];
}

+(long long)createWordId{
    long long lastWordId = [NSSTRINGTOISVALID([[NSUserDefaults standardUserDefaults] objectForKey:@"SMG_Dao_WordId_KEY"]) longLongValue];
    return lastWordId + 1;
}

-(void) updateWord:(WordConcrete*)wordC{
    if (wordC) {
        //1,本地重复词处理
        NSMutableArray *localArr = [[NSMutableArray alloc] initWithArray:[self.normalDao objectForKey:@"wordCArr"]];
        for (int i = 0; i < localArr.count; i ++) {
            WordConcrete *localWordC = localArr[i];
            if (NSSTRINGISVALID(localWordC.text) && [localWordC.text isEqualToString:wordC.text]) {
                [localArr removeObjectAtIndex:i];//这里将旧有数据删了;其实应该是放到垃圾池比较好;(可供后查)//xxx
                break;
            }
        }
        //2,更新本地wordId键值
        long long lastWordId = [NSSTRINGTOISVALID([[NSUserDefaults standardUserDefaults] objectForKey:@"SMG_Dao_WordId_KEY"]) longLongValue];
        if (lastWordId < wordC.wordId) {
            [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lld",wordC.wordId] forKey:@"SMG_Dao_WordId_KEY"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        //3,存wordC到TMCache
        [localArr addObject:wordC];
        [self.normalDao setObject:localArr forKey:@"wordCArr"];
        [[TMCache sharedCache] setObject:self.normalDao forKey:@"SMG_Dao_NORMAL_LOCAL_KEY"];
    }
}


-(WordConcrete*) getWordConcreteWithWordText:(NSString*)wordText{
    if (NSSTRINGISVALID(wordText) == false) return nil;
    NSMutableArray *oldArr = [[NSMutableArray alloc] initWithArray:[self.normalDao objectForKey:@"wordCArr"]];
    if (oldArr == nil) return nil;
    
    for (WordConcrete *wordC in oldArr) {
        if ([wordText isEqualToString:wordC.text]) {
            return wordC;
        }
    }
    return nil;
}

@end
